/*****  Component, by Ben Bi <prince.bi@gmail.com>  created at: 12/23/2009 4:10:45 PM  *****/

/********   Notes:  *******
 *  Two tags need to be replaced with the module name, they are:
 *  dispatchOrderFinalCloth
 *  DispatchOrderFinalCloth
 *  /type/finalCloth
 *  FinalCloth
 */



/***** variables declartion section, begin *****/
var dispatchOrderFinalClothInputMode = wacFormInputMode.add;
var dispatchOrderFinalClothObj = {};
var dispatchOrderFinalClothAuditAction = {};

var dispatchOrderFinalClothDataStore = {items:[]};  // to store the items
var dispatchOrderFinalCloth_goodsListCurrentPage = 1;
var dispatchOrderFinalCloth_goodsListTotalPages = 1;

/***** variables declartion section, end *****/

/***** init section, begin *****/
$(document).ready(
    function() {
        dispatchOrderFinalClothAuditAction = new DispatchOrderFinalClothAuditAction();

        initDispatchOrderFinalClothFormDialog();

        initDispatchOrderFinalClothForm();

        bindDispatchOrderFinalClothEvents();
    }
);

function bindDispatchOrderFinalClothEvents()
{
    $("#dispatchOrderFinalClothFormDialog").bind('dialogopen', function(event, ui)
    {
        initDispatchOrderFinalClothFormData();
//        wacDebugLog("calling " + moduleName + ":" + wacModelObj.dispatchOrderFinalCloth.name);//
    });

    $("#dispatchOrderFinalClothFormDialog").bind('dialogclose', function(event, ui)
    {
        $.validationEngine.closePrompt(".formError", true);
    });

    $("#dispatchOrderFinalCloth_btnSubmit").bind('click', function (e)
    {
        submitDispatchOrderFinalClothForm();
    });

    $("#dispatchOrderFinalCloth_btnClose").bind('click', function (e)
    {
        $("#dispatchOrderFinalClothFormDialog").dialog('close');
    });

    $("#dispatchOrderFinalCloth_btnPrev").bind('click', function (e)
    {
        if(dispatchOrderFinalCloth_goodsListCurrentPage>1)
        {
            dispatchOrderFinalCloth_goodsListCurrentPage--;
            if($('#dispatchOrderFinalCloth_supplier_id_hidden').val()!="")
            {
                dispatchOrderFinalClothRefleshStockGoodsList($('#dispatchOrderFinalCloth_supplier_id_hidden').val());
            }
        }
    });

    $("#dispatchOrderFinalCloth_btnNext").bind('click', function (e)
    {
        if(dispatchOrderFinalCloth_goodsListCurrentPage < dispatchOrderFinalCloth_goodsListTotalPages)
        {
            dispatchOrderFinalCloth_goodsListCurrentPage++;
            if($('#dispatchOrderFinalCloth_supplier_id_hidden').val()!="")
            {
                dispatchOrderFinalClothRefleshStockGoodsList($('#dispatchOrderFinalCloth_supplier_id_hidden').val());
            }
        }
    });

    $("#dispatchOrderFinalCloth_btnTransfer").bind('click', function (e)
    {
        dispatchOrderFinalClothTransferGoods();
    });


    // fix dialog div didnt remove bug, remove it by this way
    $('#appStorehouseRightPane').bind('tabsremove', function(event, ui) {
        if(ui.panel.id == "t17002")
        {
            $("div[aria-labelledby='ui-dialog-title-dispatchOrderFinalClothFormDialog']").remove();
            $("#dispatchOrderFinalClothFormDialog").remove();
        }
    });
}


function initDispatchOrderFinalClothFormDialog()
{
//    wacDebugLog("initDispatchOrderFinalClothFormDialog.");
    $("#dispatchOrderFinalClothFormDialog").dialog({
            bgiframe: true,
            modal: true,
            width: 860,
            height: 680,
            autoOpen: false,
            buttons: {},
            zIndex: 100
        });
}

function initDispatchOrderFinalClothForm()
{
//    wacDebugLog("initDispatchOrderFinalClothForm");
    $("#dispatchOrderFinalClothForm").validationEngine();

    $.datepicker.setDefaults($.datepicker.regional['zh-CN']);
    $("#dispatchOrderFinalCloth_delivery_date").datepicker({beforeShow: function() {$('#ui-datepicker-div').maxZIndex();}});

    $('.wacFormContent .left, .wacFormContent input, .wacFormContent textarea, .wacFormContent select').focus(function(){
        $(this).parents('.wacFormContent').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormContent').removeClass("wacFormOver");
    });

    $('.wacFormContentA .left, .wacFormContentA input, .wacFormContentA textarea, .wacFormContentA select').focus(function(){
        $(this).parents('.wacFormRow').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormRow').removeClass("wacFormOver");
    });

    // init the good list css and selectable
    $('ol#dispatchOrderFinalCloth_stockGoodsList li').hover(
        function() {
            $(this).addClass('ui-state-hover');
        },
        function() {
            $(this).removeClass('ui-state-hover');
        }
    );

    $("#dispatchOrderFinalCloth_stockGoodsList").selectable({
        stop: function(){
//            var result = $("#dispatchOrderFinalCloth_selectStockGoods").empty();
//            $(".ui-selected", this).each(function(){
//                var index = $("#dispatchOrderFinalCloth_stockGoodsList li").index(this);
//                result.append(" #" + (index + 1));
//                wacDebugLog($(this).attr("goods_id") + ": " + $(this).attr("goods_number") + ": " + $(this).html());
//            });
        }
    });

}

function initDispatchOrderFinalClothFormData()
{
    wacShowBlockUILoading("#dispatchOrderFinalClothFormDialog");
    $('#dispatchOrderFinalCloth_supplier_id, #dispatchOrderFinalCloth_target_id, #dispatchOrderFinalCloth_production_order_id, #dispatchOrderFinalCloth_goods_amount_unit_code').empty();

    var params = {"data_format" :'json'};
    if(dispatchOrderFinalClothInputMode == wacFormInputMode.add)
    {
        params.id = 0;
    }
    else
    {
        params.id = dispatchOrderFinalClothObj.id;
    }

    $.ajax({
        url: BASE_URL + "dispatchOrder/getFormData/type/finalCloth",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            initDispatchOrderFinalClothFormDataCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function initDispatchOrderFinalClothFormDataCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       alert(jsonData.info.error_info);
   }
   else
    {
        for(i=0;i<jsonData['items']['unit'].length;i++)
        {
            $('<option value="' + jsonData['items']['unit'][i].key +'">' + jsonData['items']['unit'][i].value +'</option>').appendTo("#dispatchOrderFinalCloth_goods_amount_unit_code");
        }

        var itemStr = "";
        dispatchOrderFinalClothEmptyStockGoodsList();
        if(jsonData['items']['stock_goods_items']['items']!=undefined){
            for(i=0;i<jsonData['items']['stock_goods_items']['items'].length;i++)
            {
                itemStr = dispatchOrderFinalClothSetupStockGoodsItemStr(jsonData['items']['stock_goods_items']['items'][i]);
                $(itemStr).appendTo("#dispatchOrderFinalCloth_stockGoodsList");
            }
            dispatchOrderFinalCloth_goodsListTotalPages = jsonData['items']['stock_goods_items']['totalPages'];
        }

        dispatchOrderFinalClothEmptyTargetGoodsList();
        if(jsonData['items']['target_items']['items']!=undefined){
            for(i=0;i<jsonData['items']['target_items']['items'].length;i++)
            {
                $(dispatchOrderFinalClothDataStore).data(jsonData['items']['target_items']['items'][i].goods_id, jsonData['items']['target_items']['items'][i].goods_id);

                itemStr = dispatchOrderFinalClothSetupTargetGoodsItemStr(jsonData['items']['target_items']['items'][i]);
                $(itemStr).appendTo("#dispatchOrderFinalCloth_targetGoodsList");
            }
        }
   }

   setupDispatchOrderFinalClothFormDefaultValues(jsonData['items']['default']);

   wacHideBlockUI("#dispatchOrderFinalClothFormDialog");

//   wacDebugLog($.dump(jsonData));
}

function setupDispatchOrderFinalClothFormDefaultValues(defaultValueObj)
{
    if(dispatchOrderFinalClothInputMode == wacFormInputMode.add)   // use default values
    {
        $("#dispatchOrderFinalCloth_id").attr("value", 0);
        $('#dispatchOrderFinalCloth_production_order_id').flexbox(BASE_URL + 'productionOrder/GetIdCodeHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "production_order_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $('#dispatchOrderFinalCloth_supplier_id').flexbox(BASE_URL + 'factory/GetFinalClothFactoryIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "supplier_id",
            onSelect: function() {
                $(dispatchOrderFinalClothDataStore).removeData();
                dispatchOrderFinalCloth_goodsListCurrentPage = 1;
                dispatchOrderFinalClothEmptyTargetGoodsList();
                dispatchOrderFinalClothRefleshStockGoodsList(this.getAttribute('hiddenValue'));
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $('#dispatchOrderFinalCloth_target_id').flexbox(BASE_URL + 'factory/GetCustomerFactoryIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "target_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $("#dispatchOrderFinalCloth_goods_amount_unit_code option:[value='"+ defaultValueObj.unit_code +"']").attr('selected', 'selected');
        $("#dispatchOrderFinalCloth_stockGoodsListPageBtns").hide();
    }
    else  // use edit obj values
    {
        $('#dispatchOrderFinalCloth_production_order_id').flexbox(BASE_URL + 'productionOrder/GetIdCodeHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: dispatchOrderFinalClothObj.production_order_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "production_order_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#dispatchOrderFinalCloth_production_order_id_input').val(dispatchOrderFinalClothObj.production_order_code);

        $('#dispatchOrderFinalCloth_supplier_id').flexbox(BASE_URL + 'factory/GetFinalClothFactoryIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: dispatchOrderFinalClothObj.supplier_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "supplier_id",
            onSelect: function() {
                $(dispatchOrderFinalClothDataStore).removeData();
                dispatchOrderFinalCloth_goodsListCurrentPage = 1;
                dispatchOrderFinalClothEmptyTargetGoodsList();
                dispatchOrderFinalClothRefleshStockGoodsList(this.getAttribute('hiddenValue'));
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#dispatchOrderFinalCloth_supplier_id_input').val(dispatchOrderFinalClothObj.supplier_name);

        $('#dispatchOrderFinalCloth_target_id').flexbox(BASE_URL + 'factory/GetCustomerFactoryIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: dispatchOrderFinalClothObj.target_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "target_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#dispatchOrderFinalCloth_target_id_input').val(dispatchOrderFinalClothObj.target_name);

        $("#dispatchOrderFinalCloth_delivery_date").attr("value", dispatchOrderFinalClothObj.delivery_date);
        $("#dispatchOrderFinalCloth_code").attr("value", dispatchOrderFinalClothObj.code);
        $("#dispatchOrderFinalCloth_id").attr("value", dispatchOrderFinalClothObj.id);
        $("#dispatchOrderFinalCloth_memo").attr("value", dispatchOrderFinalClothObj.memo);

        $("#dispatchOrderFinalCloth_goods_amount_unit_code option:[value='"+ dispatchOrderFinalClothObj.goods_amount_unit_code +"']").attr('selected', 'selected');
        $("#dispatchOrderFinalCloth_supplier_id option:[value='"+ dispatchOrderFinalClothObj.supplier_id +"']").attr('selected', 'selected');
        $("#dispatchOrderFinalCloth_target_id option:[value='"+ dispatchOrderFinalClothObj.target_id +"']").attr('selected', 'selected');
    }

//    wacDebugLog($.dump(dispatchOrderFinalClothObj));
//    wacDebugLog($.dump(defaultValueObj));
//    wacDebugLog("dispatchOrderFinalClothInputMode: " + dispatchOrderFinalClothInputMode);

}
/***** init section, end *****/


/**************  interaction section, begin  ***************/
// audit class
function DispatchOrderFinalClothAuditAction(){
    this.run = function(orderId){
        dispatchOrderFinalClothAudit(orderId);
    }
}

function dispatchOrderFinalClothAudit(orderId)
{
    wacShowBlockUILoading();
    var params = {
        "data_format" : 'json',
        "order_id" : orderId
    };
//    dispatchOrderFinalClothObj = $("#dispatchOrderFinalClothList").getRowData(orderId);
//    console.log($.dump(dispatchOrderFinalClothObj));

    $.ajax({
        url: BASE_URL + "dispatchOrder/audit/type/finalCloth",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            dispatchOrderFinalClothAuditCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function dispatchOrderFinalClothAuditCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#dispatchOrderFinalClothList").trigger("reloadGrid");
   }
   wacHideBlockUI();
//   wacDebugLog($.dump(jsonData));
}

function dispatchOrderFinalClothOpenModuleForm(moduleFormName, moduleName, inputMode, rowid)
{
    dispatchOrderFinalClothInputMode = inputMode;

    if(rowid === undefined){
        dispatchOrderFinalClothObj = {};
    }
    else
    {
        dispatchOrderFinalClothObj = $("#" + moduleName +"List").getRowData(rowid);
    }

    $('#'+moduleFormName).dialog('open');
}

function validateDispatchOrderFinalClothForm()
{
    var validateFlag = true;

    if (!$("#dispatchOrderFinalClothForm").validationEngine({returnIsValid:true}))
    {
        validateFlag = false;
        return validateFlag;
    }

    if($("#dispatchOrderFinalCloth_targetGoodsList li").length == 0)
    {
        wacShowTips("请输入出货货项!");
        validateFlag = false;
    }


    return validateFlag;
}

function submitDispatchOrderFinalClothForm()
{
    if(!validateDispatchOrderFinalClothForm()){
        return;
    }

    wacShowBlockUILoading("#dispatchOrderFinalClothFormDialog", "处理中...");

    var extraParams = "data_format=json";
    var submitUrl;

    if(dispatchOrderFinalClothInputMode == wacFormInputMode.add){
        submitUrl = BASE_URL + "dispatchOrder/add/type/finalCloth";
    }
    else{
        submitUrl = BASE_URL + "dispatchOrder/edit/type/finalCloth";
    }


    $.ajax({
        url: submitUrl,
//        url: BASE_URL + "test/ajaxTest" ,
        global: true,
        type: "GET",
        data: $("#dispatchOrderFinalClothForm").serialize() + "&" + extraParams,
        dataType: "json",
        success: function(jsonData){
            submitDispatchOrderFinalClothFormCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function submitDispatchOrderFinalClothFormCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       $("#dispatchOrderFinalClothFormDialog").dialog('close');
       wacShowTips(jsonData.info.tips);
       $("#dispatchOrderFinalClothList").trigger("reloadGrid");
   }

   wacHideBlockUI("#dispatchOrderFinalClothFormDialog");

//   wacDebugLog($.dump(jsonData));
}

function dispatchOrderFinalClothTransferGoods()
{
   $(".ui-selected", $("#dispatchOrderFinalCloth_stockGoodsList")).each(function(){
       if($(dispatchOrderFinalClothDataStore).data($(this).attr("goods_id")) === undefined)
       {
           $(dispatchOrderFinalClothDataStore).data($(this).attr("goods_id"), $(this).attr("goods_id"));
    //       wacDebugLog($(this).attr("goods_id") + ": " + $(this).attr("goods_number") + ": " + $(this).html());
            var itemStr = dispatchOrderFinalClothSetupTargetGoodsItemStr(this);
            $(itemStr).appendTo("#dispatchOrderFinalCloth_targetGoodsList");
       }
   });
}

function dispatchOrderFinalClothSetupTargetGoodsItemStr(objItem)
{
   var tmpStr = '<li class="ui-widget-content wacCursor">' + $(objItem).attr("goods_name") ;
                tmpStr += '&nbsp;<input type="text" id="dispatchOrderFinalCloth_id_' + $(objItem).attr("goods_id") +'" name="target_goods[id_' + $(objItem).attr("goods_id") + ']" value="' + $(objItem).attr("goods_number") + '" maxNumber="' + $(objItem).attr("goods_number") + '" class="validate[required,custom[onlyNumber]] wacFormText" style="width: 45px;">';
                tmpStr += '<span class="ui-icon ui-icon-circle-minus" style="float:right" onclick="javascript: dispatchOrderFinalClothRemoveItem(this, '+ $(objItem).attr("goods_id") +');"></span>';
                tmpStr += '</li>';
    return tmpStr;
}

function dispatchOrderFinalClothRemoveItem(tagObj, goodId)
{
    $(tagObj).parent().remove();
    $(dispatchOrderFinalClothDataStore).removeData(goodId);
}

function dispatchOrderFinalClothSetupStockGoodsItemStr(objItem)
{
    var tmpStr = '<li class="ui-widget-content wacCursor" goods_id="' + $(objItem).attr("goods_id") +'" goods_number="' + $(objItem).attr("goods_number")+' "';
            tmpStr += 'goods_name="' + $(objItem).attr("goods_name") + ' " goods_number_unit_code_name="' + $(objItem).attr("goods_number_unit_code_name") +'" >';
            tmpStr += $(objItem).attr("goods_name") + "&nbsp;" + $(objItem).attr("goods_number") + "&nbsp;" + $(objItem).attr("goods_number_unit_code_name") +'</li>';
    return tmpStr;
}

function dispatchOrderFinalClothRefleshStockGoodsList(id)
{
    wacShowBlockUILoading("#dispatchOrderFinalCloth_stockGoodsZone", "装载中...");

    var submitUrl;
    var params = {
        "data_format" : 'json',
        "factory_id" : id,
        "rows" : 10,
        "page" : dispatchOrderFinalCloth_goodsListCurrentPage
    };

    submitUrl = BASE_URL + "factory/GetStockGoodsListByDispatchOrderType/type/finalCloth";
//    submitUrl = BASE_URL + "test/ajaxTest";
    $.ajax({
        url: submitUrl,
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            dispatchOrderFinalClothRefleshStockGoodsListCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function dispatchOrderFinalClothRefleshStockGoodsListCallBack(jsonData)
{
    if(jsonData.info.status == wacOperationStatus.Error)
    {
        wacShowTips(jsonData.info.error_info);
    }
    else
    {
        dispatchOrderFinalCloth_goodsListTotalPages = jsonData.totalPages;
        if(dispatchOrderFinalCloth_goodsListTotalPages > 1){
            $("#dispatchOrderFinalCloth_stockGoodsListPageBtns").show();
        }
        dispatchOrderFinalClothEmptyStockGoodsList();
        for(i=0;i<jsonData['items'].length;i++)
        {
            var itemStr = dispatchOrderFinalClothSetupStockGoodsItemStr(jsonData['items'][i]);
            $(itemStr).appendTo("#dispatchOrderFinalCloth_stockGoodsList");
        }
//        wacShowTips(jsonData.info.tips);
    }

    wacHideBlockUI("#dispatchOrderFinalCloth_stockGoodsZone");
}

function dispatchOrderFinalClothEmptyStockGoodsList()
{
    $("#dispatchOrderFinalCloth_stockGoodsZone li").remove();
}

function dispatchOrderFinalClothEmptyTargetGoodsList()
{
    $("#dispatchOrderFinalCloth_targetGoodsZone li").remove();
}
/**************  interaction section, end  ***************/